$(function () {
    var $table = $('#userLists');
    action = "addUser";
    var oTable = new TableInit($table, '/UserManage/getUserList');
    oTable.Init();


    var oButtonInit = new ButtonInit($table, action);
    oButtonInit.Init();


    var icon = {
        valid: 'glyphicon glyphicon-ok',
        invalid: 'glyphicon glyphicon-remove',
        validating: 'glyphicon glyphicon-refresh'
    };

    $("form[name='userForm']").bootstrapValidator({
        feedbackIcons: icon,
        live: 'enabled',
        //表单域配置
        fields: {
            txtUsername: {
                validators: {
                    notEmpty: {message: '请输入用户名'},
                    stringLength: {
                        min: 2,
                        max: 30,
                        message: '用户名长度必须在2到30之间'
                    },
                    remote: {
                        url: '/portal/checkaccount',
                        message: '用户名已存在',
                        type: 'POST'
                    }
                }
            },
            txtFullName: {
                validators: {
                    notEmpty: {message: "请输入姓名"}
                }
            },
            txtPasswd: {
                validators: {
                    notEmpty: {message: '请输入密码'},
                    regexp: {
                        regexp: /(?=.*[A-Z])(?=.*[a-z])(?=.*[0-9])[A-Za-z0-9]{8,16}/,
                        message: '密码长度大于8小于16，且包括大小写字母、数字'
                    }
                }
            },
            txtPasswdConfirm: {
                validators: {
                    notEmpty: {message: '请再次输入密码'},
                    identical: {
                        field: 'txtPasswd',
                        message: '两次密码不一致'
                    }
                }
            },
            userRole: {
                validators: {
                    notEmpty: {
                        message: "请选择用户角色"
                    },
                    callback: {
                        message: "必须选择一个用户角色",
                        callback: function (value, validator) {
                            if (value == "")
                                return false;
                            else
                                return true;
                        }
                    }
                }
            },
            txtMobile: {
                validators: {
                    notEmpty: {
                        message: "请输入电话号码"
                    },
                    regexp: {
                        regexp: /(^(\d{3,4}-)?\d{6,8}$)|(^(\d{3,4}-)?\d{6,8}(-\d{1,5})?$)|^(((13[0-9]{1})|(15[0-9]{1})|(18[0-9]{1})|(17[0-9]{1}))+\d{8})$/,
                        message: '请输入正确的电话号码'
                    },
                    remote: {
                        url: '/portal/checkphone',
                        message: '电话号码已存在',
                        type: 'POST',
                        data: {
                            username: function () {
                                return $("#txtUsername").val();
                            },
                            txtMobile: function () {
                                return $("#txtMobile").val();
                            }
                        }
                    }
                }
            },
            txtEmail: {
                validators: {
                    emailAddress: {message: '请输入正确的邮件地址'}
                }
            }
        }
    })

});


var TableInit = function ($table, url) {
    var oTableInit = new Object();

    oTableInit.Init = function () {
        $table.bootstrapTable({
            url: url,
            method: 'get',
            striped: true,
            cache: false,
            pagination: true,
            sortable: false,
            sortOrder: "asc",
            queryParams: oTableInit.queryParams,
            sidePagination: "server",
            search: false,
            pageNumber: 1,
            pageSize: 20,
            pageList: [1, 10, 20, 50, 100],
            strictSearch: true,
            showColumns: true,
            showRefresh: true,
            minimumCountColumns: 2,
            clickToSelect: true,
            uniqueId: "id",
            showToggle: true,
            cardView: false,
            detailView: false,
            columns: [{
                checkbox: true
            },
                {
                    title: '序号',
                    align: 'center',
                    halign: 'center',
                    formatter: function (value, row, index) {
                        var options = $table.bootstrapTable('getOptions');
                        return options.pageSize * (options.pageNumber - 1) + index + 1;
                    }
                },
                {
                    field: 'id',
                    title: '用户id',
                    visible: false
                }, {
                    field: 'name',
                    title: '用户名'
                }, {
                    field: 'relname',
                    title: '名字'
                }, {
                    field: 'phone',
                    title: '手机号'
                },
                {
                    field: 'pic',
                    title: '头像',
                    align: 'center',
                    formatter: function (value, row, index) {
                        return '<img src="' + value + '" width="26px">';
                    }
                },
                {
                    field: 'sex',
                    title: '性别',
                    formatter: function (value, row, index) {
                        return value == 0 ? '女' : '男';
                    }
                },
                {
                    field: 'email',
                    title: '邮箱'
                },
                {
                    field: 'time',
                    title: '添加时间'
                }
            ]
        });
    };

    oTableInit.queryParams = function (params) {
        var temp = {
            limit: params.limit,
            offset: params.offset,
            serUserRole: $("#serUserRole").val(),
            serGender: $("#serGender").val(),
            serFullName: $("#serFullName").val(),
            serMobile: $("#serMobile").val()
        };
        return temp;
    };
    return oTableInit;
};


var ButtonInit = function ($table) {
    var oInit = new Object();
    var postdata = {};

    oInit.Init = function () {
        $("#addUser").click(function () {
            action = "addUser";
            $("#txtPasswd").attr("placeholder", "请输入密码");
            $("#txtUsername").attr("disabled", false);
            $("#editUserDialog").modal("show");
        });

        $('#editUserDialog').on('hide.bs.modal', function () {
            var $formObj = $("form[name='userForm']");
            $formObj.data('bootstrapValidator').resetForm();
            $formObj[0].reset();
        });

        $("#serBtn").click(function () {
            $table.bootstrapTable("refresh");
        });

        $("#editUser").click(function () {
            action = "editUser";
            var selRows = $table.bootstrapTable('getSelections');
            var ids = [];
            if (selRows.length !== 1) {
                bootbox.alert("<h4 class='caption-subject font-red-sunglo'><i class='glyphicon glyphicon-exclamation-sign'></i> 请选择一个需要编辑的用户！</h4>");
                return;
            }
            for (var k in selRows) ids.push(selRows[k]['id']);
            $.ajax({
                type: 'get',
                data: {
                    ids: JSON.stringify(ids)
                },
                url: '/UserManage/get_user',
                beforeSend: function () {
                    $("#beforeSend").modal('show');
                },
                success: function (ret) {
                    if (ret.ret === 0) {
                        var userObj = ret.data;
                        $("#txtUsername").val(userObj["username"]);
                        $("#txtFullName").val(userObj["full_name"]);
                        if (userObj["gender"]) $("#gender").find("option[value=" + userObj["gender"] + "]").prop("selected", true);
                        if (userObj["group_id"]) $('#selUserGroup').selectpicker('val', userObj["group_id"].split(","));

                        if (userObj["user_role"]) $("#userRole").find("option[value=" + userObj["user_role"] + "]").prop("selected", true);
                        $("#txtMobile").val(userObj["mobile"]);
                        $("#txtEmail").val(userObj["email"]);

                        $("#txtPasswd").attr("placeholder", "如果不修改，请留空");
                        $("#txtUsername").attr("disabled", true);
                        $("#editUserDialog").modal("show");
                    } else {
                        noty({
                            text: '<span>' + ret.msg + '[' + ret.ret + ']' + '</span>',
                            type: 'success',
                            layout: 'topCenter',
                            closeWith: ['hover', 'click', 'button']
                        });
                    }
                },
                complete: function () {
                    $("#beforeSend").modal('hide');
                }
            });
        });

        $("#delUser").click(function () {
            var selRows = $table.bootstrapTable('getSelections');
            var ids = [];
            if (selRows.length === 0) {
                bootbox.alert("<h4 class='caption-subject font-red-sunglo'><i class='glyphicon glyphicon-exclamation-sign'></i> 请选择需要删除的用户！</h4>");
                return;
            }

            for (var k in selRows) ids.push(selRows[k]['id']);

            bootbox.dialog({
                message: "<h4 class='caption-subject font-red-sunglo'><i class='glyphicon glyphicon-exclamation-sign'></i> 是否删除所选用户？</h4>",
                buttons: {
                    OK: {
                        label: "确定",
                        className: "btn-info",
                        callback: function () {
                            $.post('/UserManage/del_user', {ids: JSON.stringify(ids)}, function (ret) {
                                noty({
                                    text: '<span>' + ret.msg + '[' + ret.ret + ']' + '</span>',
                                    type: 'success',
                                    layout: 'topCenter',
                                    closeWith: ['hover', 'click', 'button']
                                });
                                $('#userLists').bootstrapTable("refresh");
                            });
                        }
                    },
                    Cancel: {
                        label: "取消",
                        className: "btn",
                        callback: function () {

                        }
                    }
                },
                onEscape: true
            });
        });

        $("#addUserBtn").click(function (e) {
            e.preventDefault();
            var validator = $("form[name='userForm']").data("bootstrapValidator");
            if ($('#txtUsername').is(':enabled')) {
                validator.validateField("txtUsername");
                validator.validateField("fullName");
                validator.validateField("txtPasswd");
                validator.validateField("userRole");
                validator.validateField("txtMobile");
            } else {
                validator.validateField("fullName");
                validator.validateField("userRole");
                validator.validateField("txtMobile");
            }

            if ($("#txtEmail").val()) {
                validator.validateField("txtEmail");
            }

            if (validator.getInvalidFields().length === 0) {
                var params = {};
                if (action === "editUser") {
                    var id = 0;
                    var selRows = $table.bootstrapTable('getSelections');
                    for (var k in selRows) id = selRows[k]['id'];
                    params.id = id;
                }
                params.action = action;

                params.txtUsername = $("#txtUsername").val();
                params.txtFullName = $("#txtFullName").val();
                if ($("#txtPasswd").val()) params.txtPasswd = md5($("#txtPasswd").val());
                params.gender = $("#gender").val();
                params.userRole = $("#userRole").val();
                params.selUserGroup = $("#selUserGroup").val();
                if (['group_admin', 'member'].indexOf(params.userRole) && !params.selUserGroup) {
                    bootbox.alert("<h4 class='caption-subject font-red-sunglo'><i class='glyphicon glyphicon-exclamation-sign'></i> 请选择用户所属的组！</h4>");
                    return;
                }
                params.txtMobile = $("#txtMobile").val();
                params.txtEmail = $("#txtEmail").val();

                $.ajax({
                    type: 'post',
                    data: params,
                    url: '/UserManage/edit_user',
                    beforeSend: function () {
                        $("#beforeSend").modal('show');
                    },
                    success: function (ret) {
                        $("#editUserDialog").modal("hide");
                        noty({
                            text: '<span>' + ret.msg + '[' + ret.ret + ']' + '</span>',
                            type: 'success',
                            layout: 'topCenter',
                            closeWith: ['hover', 'click', 'button']
                        });
                        $('#userLists').bootstrapTable("refresh");
                    },
                    complete: function () {
                        $("#beforeSend").modal('hide');
                    }
                });
            }
        });
    };

    return oInit;
};